package com.huiyin.ui.user;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonSyntaxException;
import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.api.CustomResponseHandler;
import com.huiyin.api.RequstClient;
import com.huiyin.base.BaseActivity;
import com.huiyin.bean.AddressItem;
import com.huiyin.ui.fillorder.FillOrderActivity;
import com.huiyin.utils.AppManager;
import com.huiyin.utils.DWSqliteUtils;
import com.huiyin.utils.LocationUtil;
import com.huiyin.utils.LogUtil;
import com.huiyin.utils.StringUtils;

public class AddressModifyActivity extends BaseActivity {

	public static String TAG = "AddressModifyActivity";
	//add by zhyao @2016/6/23 是否直接弹出实名认证对话框
	public static String IS_NEED_VALIDATED = "isNeedValidated";
	
	private static final int REQUEST_CODE = 1;

	public static String ADD = "1", MODIFY = "2", UNLOGIN = "3", INIT = "4";
	TextView left_rb, middle_title_tv;
	private Spinner province, city, country;
	private static String databasepath = "/data/data/%s/databases";
	private Cursor cursorProvince = null;
	private Cursor cursorCity = null;
	private Cursor cursorArea = null;
	// 省、市、县适配器
	private SimpleCursorAdapter adapterProvince = null;
	private SimpleCursorAdapter adapterCity = null;
	private SimpleCursorAdapter adapterArea = null;

	public SQLiteDatabase mDatabase;
	// 省市县id
	private String provinceId, cityId, areaId;

	private String provinceName, cityName, areaName;
	// 收货人、手机号码、邮编地址、详细地址
	EditText address_receiver, address_modify_phone, address_modify_code, address_modify_addr;
	TextView address_modify_sure;
	// 收货人、手机号码、邮编地址、详细地址、地址id
	String receiver, phone, code, detail_addr, addressId;
	private Toast mToast;
	private String which;
	// 修改地址时从上页传过来的地址信息
	private AddressItem addressItem;

	private TextView address_detail_tv;

	private ImageView province_img, city_img, area_img;

	// 定位相关
	private String cityNameByLocation;
	
	// add by zhyao @2015/6/22 添加是不是全部消费卷字段
    private boolean isAllConsumption = false;
    private TextView address_provice_city_tv;

    //add by zhyao @2016/5/28新增实名认证
    private Button certification_btn;
    //身份证号码
    private String identificationCode;
    //身份证正面照片地址
	private String identificationPositiveUrl;
	//身份证反面照片地址
	private String identificationInverseUrl;
	//是否实名认证
	private String is_validated;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.address_modify_add);

		initView();
	}

	private void showToast(int resId) {
		if (mToast == null) {
			mToast = Toast
					.makeText(getBaseContext(), resId, Toast.LENGTH_SHORT);
		}
		mToast.setText(resId);
		mToast.show();
	}

	private boolean checkInfo() {

		receiver = address_receiver.getText().toString();
		phone = address_modify_phone.getText().toString();
		code = address_modify_code.getText().toString();
		detail_addr = address_modify_addr.getText().toString();

		if (StringUtils.isBlank(receiver)) {
			showToast(R.string.receiver_is_null);
			return false;
		} else if (StringUtils.isBlank(phone)) {
			showToast(R.string.phone_is_null);
			return false;
		} else if (!StringUtils.isPhoneNumber(phone)) {
			showToast(R.string.yuyue_phone_number_regx);
			return false;
		} 
		// modify by zhyao @2015/6/22 修改判断详细地址，当商品全部是消费卷时地址可以不填
		else if (StringUtils.isBlank(detail_addr) && !isAllConsumption) {
			showToast(R.string.addr_is_null);
			return false;
		}

		return true;
	}

	/**
	 * 修改地址
	 * 
	 */

	private void doModifyAddr() {

		String levelAddr = provinceName + cityName + areaName;
		if (AppContext.userId == null) {
			return;
		}
		
		// add by zhyao @2015/6/22 全部是消费卷，详情地址没有填写的情况下，将省、市、详细地址设置为空字符
		if(isAllConsumption && TextUtils.isEmpty(detail_addr)) {
			levelAddr = "";
			detail_addr = "";
			cityId = "";
			provinceId = "";
			areaId = "";
			addressId = "";
		}

		RequstClient.postModifyAddress(AppContext.userId, cityId, phone,
				detail_addr, receiver, code, areaId, provinceId, addressId, "", levelAddr, 
				identificationCode, identificationPositiveUrl, identificationInverseUrl, new CustomResponseHandler(this) {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						super.onSuccess(statusCode, headers, content);
						LogUtil.i(TAG, "postModifyAddress:" + content);
						try {
							JSONObject obj = new JSONObject(content);
							if (!obj.getString("type").equals("1")) {
								String errorMsg = obj.getString("msg");
								Toast.makeText(getBaseContext(), errorMsg,
										Toast.LENGTH_SHORT).show();
								return;
							}

							Intent i;
							if (which.equals(INIT) || which.equals(ADD)) {

								i = new Intent(AddressModifyActivity.this, FillOrderActivity.class);
								
							} else {
								i = new Intent(AddressModifyActivity.this,
										AddressManagementActivity.class);
							}
							AddressItem item = new AddressItem();
							item.CITY_ID = cityId;
							item.ADDRESSID = obj.getString("returnId");
							item.CONSIGNEE_PHONE = phone;
							item.ADDRESS = detail_addr;
							item.CONSIGNEE_NAME = receiver;
							item.POSTAL_CODE = code;
							item.AREA_ID = areaId;
							item.PROVINCE_ID = provinceId;
							item.LEVELADDR = provinceName + cityName
									+ areaName;
							//add by zhyao @2016/6/13 添加是否实名认证
							if (obj.has("address")) {
								JSONObject addressObj = obj.getJSONObject("address");
								if(addressObj.has("IS_VALIDATED")) {
									item.IS_VALIDATED = addressObj.getString("IS_VALIDATED");
								}
							}
							
							i.putExtra("addr", item);
							setResult(RESULT_OK, i);
							if (which.equals(MODIFY)) {
								Toast.makeText(getBaseContext(), "修改成功！",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(getBaseContext(), "增加成功！",
										Toast.LENGTH_SHORT).show();
							}

							AppManager.getAppManager().finishActivity();
							finish();

						} catch (JsonSyntaxException e) {
							e.printStackTrace();
						} catch (JSONException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
	}

	private void initView() {

		which = getIntent().getStringExtra(TAG);

		province = (Spinner) findViewById(R.id.address_modify_province);
		city = (Spinner) findViewById(R.id.address_modify_city);
		country = (Spinner) findViewById(R.id.address_modify_country);

		province_img = (ImageView) findViewById(R.id.province_img);
		city_img = (ImageView) findViewById(R.id.city_img);
		area_img = (ImageView) findViewById(R.id.area_img);

		province_img.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				province.performClick();
			}
		});

		city_img.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				city.performClick();
			}
		});

		area_img.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				country.performClick();
			}
		});

		left_rb = (TextView) findViewById(R.id.ab_back);
		left_rb.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				AppManager.getAppManager().finishActivity();
				finish();
			}
		});

		middle_title_tv = (TextView) findViewById(R.id.ab_title);

		if (which.equals(MODIFY)) {
			addressId = getIntent().getStringExtra("addressId");
			middle_title_tv.setText("地址修改");
			addressItem = (AddressItem) getIntent().getSerializableExtra("addressItem");
			identificationCode = addressItem.ID_CARD_NUMBER;
			identificationPositiveUrl = addressItem.CARD_FRONT_IMG;
			identificationInverseUrl = addressItem.CARD_BACK_IMG;
			

		} else if (which.equals(UNLOGIN)) {
			middle_title_tv.setText("地址管理");
			addressId = "";
		} else {
			middle_title_tv.setText("添加地址");
			addressId = "";
		}

		if (AppContext.isFirstCopy) {
			copyData();// 拷贝assets目录下的数据库到databases目录下
		}

		DWSqliteUtils instance = DWSqliteUtils.getInstance();
		mDatabase = instance.mDatabase;

		cursorProvince = mDatabase.rawQuery(
				"SELECT _id,parentId,areaName,level from area_table"
						+ " where level = ?", new String[] { "1" });
		adapterProvince = new SimpleCursorAdapter(this, R.layout.spinner_item,
				cursorProvince, new String[] { "areaName" },
				new int[] { R.id.text_name });

		province.setAdapter(adapterProvince);
		province.setOnItemSelectedListener(new ItemProvinceListenerImpl());

		address_receiver = (EditText) findViewById(R.id.address_receiver);
		address_modify_phone = (EditText) findViewById(R.id.address_modify_phone);
		address_modify_code = (EditText) findViewById(R.id.address_modify_code);
		address_modify_addr = (EditText) findViewById(R.id.address_modify_addr);
		
		address_detail_tv = (TextView) findViewById(R.id.address_detail_tv);

		address_modify_sure = (TextView) findViewById(R.id.address_modify_sure);
		address_modify_sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (checkInfo()) {
					if (AppContext.userId == null) {

						Intent i = new Intent();
						i.setClass(AddressModifyActivity.this,
								FillOrderActivity.class);
						i.putExtra("receiver", receiver);
						i.putExtra("phone", phone);
						i.putExtra("code", code);
						i.putExtra("detail_addr", detail_addr);
						i.putExtra("address", provinceName + cityName
								+ areaName + detail_addr);
						i.putExtra("provinceId", provinceId);
						i.putExtra("cityId", cityId);
						i.putExtra("areaId", areaId);
						setResult(RESULT_OK, i);
						AppManager.getAppManager().finishActivity();
						finish();

					} else {
						doModifyAddr();
					}

				}
			}
		});

		if (which.equals(MODIFY)) {

			address_receiver.setText(addressItem.CONSIGNEE_NAME);
			CharSequence text = address_receiver.getText();
			if (text instanceof Spannable) {
				Spannable spanText = (Spannable) text;
				Selection.setSelection(spanText, text.length());
			}
			address_modify_phone.setText(addressItem.CONSIGNEE_PHONE);
			address_modify_code.setText(addressItem.POSTAL_CODE);
			address_modify_addr.setText(addressItem.ADDRESS);

			provinceId = addressItem.PROVINCE_ID;
			cityId = addressItem.CITY_ID;
			areaId = addressItem.AREA_ID;
			addressId = addressItem.ADDRESSID;
			is_validated = addressItem.IS_VALIDATED;

			cursorProvince.moveToFirst();

			for (int i = 0; i < cursorProvince.getCount(); i++) {
				int nameColumnIndex = cursorProvince.getColumnIndex("_id");
				int id = cursorProvince.getInt(nameColumnIndex);

				if ((id + "").equals(provinceId)) {
					province.setSelection(cursorProvince.getPosition());
					break;
				} else {
					cursorProvince.moveToNext();
				}
			}
			
			//add by zhyao @2016/6/23 实名认证进入，直接弹出实名认证对话框
			if(getIntent().getBooleanExtra(IS_NEED_VALIDATED, false)) {
				Intent intent = new Intent(AddressModifyActivity.this, IdentificationActivityDialog.class);
				intent.putExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_CODE, identificationCode);
				intent.putExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_POSITIVE, identificationPositiveUrl);
				intent.putExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_INVERSE, identificationInverseUrl);
				
				startActivityForResult(intent, REQUEST_CODE);
				overridePendingTransition(R.anim.popwindow_in, R.anim.popwindow_out);
			}

		} else {
			HashMap<String, String> locationMap = LocationUtil.getCurrentLocation(mContext);
			cityNameByLocation = locationMap.get("cityName");
			if (StringUtils.isBlank(cityNameByLocation)) {
				//StartLoacation();
			} else {
				setTheProvince();
			}
		}
		
		// add by zhyao @2015/6/22 添加是不是全部消费卷字段
		isAllConsumption = getIntent().getBooleanExtra("isAllConsumption", false);
		Log.d(TAG, "initview isAllConsumption = " + isAllConsumption);
		address_provice_city_tv = (TextView) findViewById(R.id.address_provice_city_tv);
		if(isAllConsumption) {
			//修改地址必填项为选填项
			address_detail_tv.setText("详细地址：");
			address_provice_city_tv.setText("省份市区：");
		}
		
		//add by zhyao @2016/5/28新增实名认证
		certification_btn = (Button) findViewById(R.id.btn_certification);
		certification_btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(AddressModifyActivity.this, IdentificationActivityDialog.class);
				intent.putExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_CODE, identificationCode);
				intent.putExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_POSITIVE, identificationPositiveUrl);
				intent.putExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_INVERSE, identificationInverseUrl);
				
				startActivityForResult(intent, REQUEST_CODE);
				overridePendingTransition(R.anim.popwindow_in, R.anim.popwindow_out);
			}
		});
		//add by zhyao @2016/5/30 判断是否实名认证
		if("1".equals(is_validated)) {
			certification_btn.setSelected(true);
			certification_btn.setText("已实名认证");
		}
		else {
			certification_btn.setSelected(false);
			certification_btn.setText("点击实名认证");
		}
		
	}

	private class ItemProvinceListenerImpl implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {

			cursorProvince.moveToPosition(arg2);
			int nameColumnIndex = cursorProvince.getColumnIndex("_id");
			int id = cursorProvince.getInt(nameColumnIndex);
			provinceId = id + "";
			// 省份名字
			int index = cursorProvince.getColumnIndex("areaName");
			provinceName = cursorProvince.getString(index);

			cursorCity = mDatabase.rawQuery(
					"SELECT _id,parentId,areaName,level from area_table"
							+ " where parentId = ?", new String[] { id + "" });

			adapterCity = new SimpleCursorAdapter(AddressModifyActivity.this,
					R.layout.spinner_item, cursorCity,
					new String[] { "areaName" }, new int[] { R.id.text_name });

			city.setAdapter(adapterCity);
			city.setOnItemSelectedListener(new ItemCityListenerImpl());

			if (which.equals(MODIFY)) {
				cursorCity.moveToFirst();
				for (int i = 0; i < cursorCity.getCount(); i++) {
					int ColumnIndex = cursorCity.getColumnIndex("_id");
					int mId = cursorCity.getInt(ColumnIndex);

					if ((mId + "").equals(cityId)) {
						city.setSelection(cursorCity.getPosition());
						break;
					} else {
						cursorCity.moveToNext();
					}
				}

			} else {
				cursorCity.moveToFirst();
				for (int i = 0; i < cursorCity.getCount(); i++) {
					int ColumnIndex = cursorCity.getColumnIndex("areaName");
					String temp = cursorCity.getString(ColumnIndex);
					if (temp.equals(cityNameByLocation)) {
						city.setSelection(cursorCity.getPosition());
						break;
					} else {
						cursorCity.moveToNext();
					}
				}
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}

	private class ItemCityListenerImpl implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			cursorCity.moveToPosition(arg2);
			int nameColumnIndex = cursorCity.getColumnIndex("_id");
			int id = cursorCity.getInt(nameColumnIndex);
			cityId = id + "";
			// 城市名字
			int index = cursorCity.getColumnIndex("areaName");
			cityName = cursorCity.getString(index);

			cursorArea = mDatabase.rawQuery(
					"SELECT _id,parentId,areaName,level from area_table "
							+ "where parentId = ?", new String[] { id + "" });

			adapterArea = new SimpleCursorAdapter(AddressModifyActivity.this,
					R.layout.spinner_item, cursorArea,
					new String[] { "areaName" }, new int[] { R.id.text_name });

			country.setAdapter(adapterArea);
			country.setOnItemSelectedListener(new ItemAreaListenerImpl());
			if (which.equals(MODIFY)) {
				cursorArea.moveToFirst();
				for (int i = 0; i < cursorArea.getCount(); i++) {
					int ColumnIndex = cursorArea.getColumnIndex("_id");
					int mId = cursorArea.getInt(ColumnIndex);
					if ((mId + "").equals(areaId)) {
						country.setSelection(cursorArea.getPosition());
						break;
					} else {
						cursorArea.moveToNext();
					}
				}
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}

	}

	private class ItemAreaListenerImpl implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			cursorArea.moveToPosition(arg2);
			int nameColumnIndex = cursorArea.getColumnIndex("_id");
			int id = cursorArea.getInt(nameColumnIndex);
			// 地区名字
			int index = cursorArea.getColumnIndex("areaName");
			areaName = cursorArea.getString(index);
			areaId = id + "";
//			address_detail_tv.setText(String.format(
//					getString(R.string.addr_detail_info), provinceName
//							+ cityName + areaName));
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (cursorProvince != null) {
			cursorProvince.close();
		} else if (cursorCity != null) {
			cursorCity.close();
		} else if (cursorArea != null) {
			cursorArea.close();
		} else if (mDatabase != null) {
			mDatabase.close();
		}

	}

	public void copyData() {
		InputStream in = null;
		FileOutputStream out = null;
		String dpath = String.format(databasepath,
				this.getApplicationInfo().packageName);
		String path = dpath + "/huiyin_db.db";
		Log.e("path", path);
		File file = new File(dpath);
		File fileData = new File(path);
		if (!fileData.exists()) {
			try {
				if (!file.exists()) {
					file.mkdir();
				}
				in = this.getAssets().open("huiyin_db.db");
				out = new FileOutputStream(fileData);
				int length = -1;
				byte[] buf = new byte[1024];
				while ((length = in.read(buf)) != -1) {
					out.write(buf, 0, length);
				}
				out.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				AppContext.isFirstCopy = false;
				if (in != null) {
					try {
						in.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
				if (out != null) {
					try {
						out.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		}
	}

//	private void StartLoacation() {
//		UIHelper.showLoadDialog(this, "定位中");
//		AppContext.getInstance().StartLoacation(new LocationCallBack() {
//
//			@Override
//			public void getPoistion(BDLocation location) {
//				UIHelper.cloesLoadDialog();
//				Toast.makeText(mContext, "定位成功", Toast.LENGTH_SHORT).show();
//				cityName = location.getCity();
//				if (!StringUtils.isBlank(cityName)) {
//					setTheProvince();
//				}
//			}
//		});
//	}

	private void setTheProvince() {
		cityNameByLocation = cityNameByLocation.replaceAll("市", "");
		Cursor checkTheCity = mDatabase.query("area_table", null,
				"areaName like ?", new String[] { cityNameByLocation }, null,
				null, null);
		while (checkTheCity.moveToNext()) {
			cursorProvince.moveToFirst();
			for (int i = 0; i < cursorProvince.getCount(); i++) {
				int nameColumnIndex = cursorProvince.getColumnIndex("_id");
				int id = cursorProvince.getInt(nameColumnIndex);
				if ((id + "").equals(checkTheCity.getString(checkTheCity
						.getColumnIndex("parentId")))) {
					province.setSelection(cursorProvince.getPosition());
					break;
				} else {
					cursorProvince.moveToNext();
				}
			}
		}
		checkTheCity.close();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == REQUEST_CODE && resultCode == IdentificationActivityDialog.RESULT_CODE) {
			identificationCode = data.getStringExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_CODE);
			identificationPositiveUrl = data.getStringExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_POSITIVE);
			identificationInverseUrl = data.getStringExtra(IdentificationActivityDialog.INTENT_KEY_IDENTIFICATION_INVERSE);
		}
	}
}
